package com.sophialex.health.record.common.audio;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class PlayAudio implements Runnable {
	private File file;
	private String path;
	private String[] names;
	private Thread td;

	/**
	 * 播放音频
	 * 
	 * @param fileName
	 */
	public void play(String fileName) {
		file = new File(fileName);
		play();
	}

	public PlayAudio(String path, String[] names) {
		this.path = path;
		this.names = names;
	}

	public static void play(String path, String[] names) {
		PlayAudio audio = new PlayAudio(path, names);
		audio.start();
	}

	/**
	 * 播放音频
	 * 
	 * @param file
	 */
	@SuppressWarnings("static-access")
	public void play() {
		try {
			AudioInputStream io = AudioSystem.getAudioInputStream(file);
			if (io instanceof AudioInputStream) {
				try {
					AudioInputStream stream = (AudioInputStream) io;
					AudioFormat format = stream.getFormat();

					/**
					 * we can't yet open the device for ALAW/ULAW playback,
					 * convert ALAW/ULAW to PCM
					 */
					if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
							|| (format.getEncoding() == AudioFormat.Encoding.ALAW)) {
						AudioFormat tmp = new AudioFormat(
								AudioFormat.Encoding.PCM_SIGNED, format
										.getSampleRate(), format
										.getSampleSizeInBits() * 2, format
										.getChannels(),
								format.getFrameSize() * 2, format
										.getFrameRate(), true);
						stream = AudioSystem.getAudioInputStream(tmp, stream);
						format = tmp;
					}
					DataLine.Info info = new DataLine.Info(Clip.class, stream
							.getFormat(),
							((int) stream.getFrameLength() * format
									.getFrameSize()));
					Clip clip = (Clip) AudioSystem.getLine(info);
					clip.open(stream);
					clip.start();
					td.sleep(2000);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		}
	}

	public void start() {
		td = new Thread(this);
		td.start();
	}

	public void run() {
		for (String name : names) {
			play(path + File.separator + name);
		}
	}

}
